import logging
import os
import shutil
import urlparse

from oriolus.trotter.core import Fetcher, FetchError

class LocalFetcher(Fetcher):
    Folder_from_install = ""
    
    def __init__(self, cache, timeout = 30):
        Fetcher.__init__(self, cache)
        self.logger = logging.getLogger("LocalFetcher")
        self.logger.debug("init fetcher: cache - '%s', timeout = %d", self.cache, timeout)

    def get(self, url, login = None, password = None):
        self.logger.info("Find folder '%s'." % LocalFetcher.Folder_from_install)
        
        if not os.path.exists(LocalFetcher.Folder_from_install):
            raise FetchError("Not found repository folder: %s" % LocalFetcher.Folder_from_install)
        
        file_name = self.__get_packet_name(url)
        file_full_name = os.path.join(LocalFetcher.Folder_from_install, file_name)
        
        shutil.copy(os.path.abspath(file_full_name), self.cache)
        
        return file_name
        
    def __get_packet_name(self, url):
        url_path = urlparse.urlparse(url).path
        return os.path.basename(url_path)
